package com.ruoyi.farmer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.agri.api.service.farmer.IFarmerProductSpecificationsService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.model.farmer.domain.FarmerProductSpecValue;
import com.ruoyi.common.model.farmer.domain.FarmerProductSpecification;
import com.ruoyi.common.model.farmer.dto.resp.FarmerSpecificationResp;
import com.ruoyi.farmer.mapper.FarmerProductSpecValueMapper;
import com.ruoyi.farmer.mapper.FarmerProductSpecificationsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author huixh
 */
@Service
public class FarmerProductSpecificationsServiceImpl implements IFarmerProductSpecificationsService {
    @Resource
    private FarmerProductSpecificationsMapper productSpecificationsMapper;

    @Resource
    private FarmerProductSpecValueMapper farmerProductSpecValueMapper;

    @Override
    public List<FarmerSpecificationResp> selectFarmerProductSpecificationsList(Long productId) {
        if (productId == null) {
            throw new ServiceException("违法请求");
        }
        List<FarmerProductSpecification> farmerProductSpecifications = productSpecificationsMapper.selectProductSpecificationsByProductId(productId);
        List<FarmerSpecificationResp> farmerSpecificationResps = BeanUtil.copyToList(farmerProductSpecifications, FarmerSpecificationResp.class);
        List<Long> specificationIds = farmerProductSpecifications.stream().map(FarmerProductSpecification::getId).collect(Collectors.toList());

        Map<Long, List<FarmerProductSpecValue>> specIdToSpecValuesMap = farmerProductSpecValueMapper.selectSpecValueBySpecIds(specificationIds)
                .stream()
                .collect(Collectors.groupingBy(FarmerProductSpecValue::getSpecificationId));

        for (FarmerSpecificationResp specification : farmerSpecificationResps) {
            List<FarmerProductSpecValue> specValues = specIdToSpecValuesMap.get(specification.getId());
            List<FarmerSpecificationResp.SpecValue> values = specValues.stream().map(specValue -> {
                FarmerSpecificationResp.SpecValue value = new FarmerSpecificationResp.SpecValue();
                value.setId(specValue.getId().intValue());
                value.setValue(specValue.getSpecificationValue());
                value.setSort(0);
                return value;
            }).collect(Collectors.toList());
            specification.setValues(values);
            specification.setValueCount(specValues.size());
        }
        return farmerSpecificationResps;
    }
}
